﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FisheryPlatform.Bussiness.WebRuntime;
using FisheryPlatform.Entity.Post;
using FisheryPlatform.Bussiness;
using FisheryPlatform.Bussiness.Term;
using FisheryPlatform.Entity;
using FisheryPlatform.Common;
using NSPosts = FisheryPlatform.Web.Admin.Modules.Post;
using FisheryPlatform.Bussiness.Post;
using FisheryPlatform.Bussiness.Option;
namespace FisheryPlatform.Web.Admin.Posts
{
    /// <summary>
    /// Action 的摘要说明
    /// </summary>
    public class Action : HttpHandlerBase, IHttpHandler
    {
        private AjaxActionResult actionResult = new AjaxActionResult();

        public void ProcessRequest(HttpContext context)
        {
            base.Init(context);
            try
            {
                #region
                var actionValue = 0;
                if (int.TryParse(FormValue("action"), out actionValue))
                {
                    switch ((PostActionEnum)actionValue)
                    {
                        case PostActionEnum.CateList: GetCateList(); break;
                        case PostActionEnum.CateNameList: GetCateNameList(); break;
                        case PostActionEnum.CateAdd:
                        case PostActionEnum.CateEdit: CateEdit(); break;
                        case PostActionEnum.TagList: GetTagList(); break;
                        case PostActionEnum.TagAdd:
                        case PostActionEnum.TagEdit: TagEdit(); break;
                        case PostActionEnum.DeleteTerm: DeleteTerm(); break;
                        case PostActionEnum.UpdateStatus: UpdateStatus(); break;
                        case PostActionEnum.HotSettings: HotSettings(); break;
                        default: actionResult.message = "未知操作" + actionValue; break;
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                ExceptionMessage.Record(ex);
            }

            SerializeDataToResponseStream(actionResult);
        }

        private void GetCateList()
        {
            GetTermListByTaxonomy(TermTaxonomyEnum.Cate);
        }

        private void GetCateNameList()
        {
            actionResult.obj = TermManager.GetPostCateList();
            actionResult.success = true;
        }

        private void CateEdit()
        {
            SaveTerm(TermTaxonomyEnum.Cate);
        }

        private void GetTagList()
        {
            GetTermListByTaxonomy(TermTaxonomyEnum.Tag);
        }

        private void TagEdit()
        {
            SaveTerm(TermTaxonomyEnum.Tag);
        }

        private void GetTermListByTaxonomy(TermTaxonomyEnum taxonomy)
        {
            #region
            var pageCount = 0;
            var pageIndex = 1;
            var pageSize = 30;
            if (!int.TryParse(FormValue("pi"), out pageIndex))
            {
                pageIndex = 1;
            }

            List<TermEntity> termList = TermManager.Search(string.Format(" Taxonomy={0}", (int)taxonomy), pageIndex, pageSize, out pageCount);
            actionResult.success = true;
            var previewManager = new UserControlPreviewManager<NSPosts.TermList>();
            NSPosts.TermList termListControl = previewManager.LoadUserControl("~/Modules/Post/TermList.ascx");
            termListControl.Taxonomy = taxonomy;
            termListControl.PostTermList = termList;
            termListControl.CurrentIndex = pageIndex;
            termListControl.PageSize = pageSize;
            termListControl.PageCount = pageCount;
            termListControl.IsForAjax = true;
            termListControl.AjaxPageClickCallback = "pageChanged({index})";

            actionResult.obj = new { html = previewManager.RenderHtml(termListControl) };
            #endregion
        }

        private void SaveTerm(TermTaxonomyEnum taxonomy)
        {
            #region
            long termId = 0;
            long.TryParse(FormValue("tremId"), out termId);

            TermEntity termInfo = new TermEntity();
            termInfo.TermId = termId;
            termInfo.Name = FormValue("name");
            termInfo.Slug = FormValue("slug");
            if (taxonomy == TermTaxonomyEnum.Cate)
            {
                termInfo.ParentId = long.Parse(FormValue("parentId"));
            }
            else
            {
                termInfo.ParentId = 0;
            }
            termInfo.Description = FormValue("desc");
            termInfo.Count = 0;
            termInfo.Taxonomy = taxonomy;
            if (!string.IsNullOrEmpty(termInfo.Name) && !TermManager.ExistName(termId, termInfo.Name, termInfo.ParentId, taxonomy))
            {
                actionResult.success = TermManager.Save(termInfo);
            }
            else
            {
                actionResult.message = "拥有相同名字的父级项目已存在。";
            }

            #endregion
        }

        private void DeleteTerm()
        {
            actionResult.success = TermManager.DeleteByTermId(long.Parse(FormValue("termId")));
        }

        private void UpdateStatus()
        {
            #region
            switch ((PostStatusEnum)int.Parse(FormValue("status")))
            {
                case PostStatusEnum.Publish: MovePostTo(PostStatusEnum.Publish); break;
                case PostStatusEnum.Trash: MovePostTo(PostStatusEnum.Trash); break;
            }
            #endregion
        }

        private void MovePostTo(PostStatusEnum status)
        {
            #region
            var ids = FormValue("ids");
            if (string.IsNullOrEmpty(ids) == false)
            {
                actionResult.success = PostManager.BatchUpdateStatus(ids, status);
            }
            #endregion
        }

        private void HotSettings()
        {
            #region
            var opName = FormValue("opName");
            var flag = FormValue("flag");
            long postId = 0;
            if (OptionNameConstants.List.Contains(opName) && long.TryParse(FormValue("id"), out postId))
            {
                actionResult.success = OptionManager.Save(opName, FormValue("id"), flag == "1" ? true : false);
            }
            #endregion
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}